package com.hbt.first.controller;

import com.hbt.first.wx.WXCore;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RestController
@Slf4j
public class MyHellow {
    String app_secret = "a1f96292cb985a542d4d832f804a0dd3";

    String appid = "wx9cab1554501087f3";

    @Autowired
    RestTemplate restTemplate;
    private String session_key;

    @GetMapping("/session/{code}")
    public String func(@PathVariable("code") String code){
        System.out.println(code);
//        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+app_secret+"&js_code="+code+"&grant_type=authorization_code";
        String url = "https://api.weixin.qq.com/sns/jscode2session?";
        Map<String, Object> wres = new HashMap<String, Object>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        wres.put("appid", appid);
        wres.put("secret", app_secret.trim());
        wres.put("js_code", code);
        wres.put("grant_type", "authorization_code");
        MultiValueMap map = new LinkedMultiValueMap();
        for(Iterator<Map.Entry<String, Object>> itr = wres.entrySet().iterator(); itr.hasNext();){
            Map.Entry<String, Object> entry = itr.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            map.add(key, value);
        }
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        try {
            ResponseEntity<String> res = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            System.out.println("res.body:"+res.getBody());
//            session_key = (String) res.getBody().get("session_key");
            JSONObject jsonObject = JSONObject.fromObject(res.getBody());
            System.out.println("key:"+jsonObject.get("session_key"));
            session_key = (String) jsonObject.get("session_key");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return "body";
    }

    @GetMapping("decode")
    public String decode(@RequestParam("encry") String encry, @RequestParam("iv")String iv){
        System.out.println("encry:"+encry);
        System.out.println("iv:"+iv);
        String s = WXCore.decrypt(appid, encry,session_key,iv);
        System.out.println("解密结果"+s);
        return s;
    }



}
